<template>
  <div class="main" style=" background-color: #fff;">
    <el-card shadow="never" style=" margin: auto;">
      <template #header>
        <div>
          <span>编辑内容</span>
        </div>
      </template>

      <el-form :model="formData" ref="formRef" :rules="rules" label-position="left" label-width="110px" size="default"
        @submit.prevent>
        <el-form-item label="标题" prop="title" class="required label-right-align">
          <el-input v-model="formData.title" type="text" clearable></el-input>
        </el-form-item>
        <el-form-item label="分类" prop="category" class="required label-right-align">
          <el-input v-model="formData.category" type="text" clearable></el-input>
        </el-form-item>
        <el-form-item label="访问地址" prop="url" class="required label-right-align">
          <el-input v-model="formData.url" type="text" clearable></el-input>
        </el-form-item>
        <el-form-item label="上传封面图 / 输入封面地址">
          <div style="display: flex;width: 100%;">
            <div>
              <!-- <el-upload :file-list="fileList" action="/api/upload/libraries/single" :on-progress="handleProgress"
                :on-success="handleSuccess" :on-error="handleError" ref="uploadComm" :show-file-list="false"
                :loading="isUploading">
                <el-button type="primary" v-if="formData.imgUrl">修改封面</el-button>
                <el-button type="primary" v-else>上传封面</el-button>
                <template #tip>
                  <div class="el-upload__tip">图片不能大于500kb</div>
                </template>
              </el-upload> -->
              <el-upload :file-list="fileList" :action=domain :show-file-list="false" :http-request=upqiniuImg
                :on-success="handleAvatarSuccess" :on-preview="handlePictureCardPreview" :before-upload="beforeUpload">
                <el-button type="primary" v-if="formData.imgUrl">修改封面</el-button>
                <el-button type="primary" v-else>上传封面</el-button>
                <template #tip>
                  <div class="el-upload__tip">图片不能大于500kb</div>
                </template>
              </el-upload>
            </div>
            <div style="width: 100%;flex: 1;">
              <el-input v-model="formData.img" type="text" placeholder="请输入封面地址" style="width: 100%;"></el-input>
            </div>
          </div>
          <div>
            <img v-if="formData.img" :src="formData.img" class="avatar" @click="handlePictureCardPreview"
              style="max-height:200px">
          </div>
        </el-form-item>
        <el-form-item label="背景底色" prop="bgColor" class="label-right-align">
          <div style="display: flex;">
            <el-input type="color" v-model="formData.bgColor" size="small" placeholder="请选择背景底色" style="width:100px">
            </el-input>
            <el-input v-model="formData.bgColor" type="text" placeholder="请输入背景底色"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="描述" prop="descriptions" class="required label-right-align">
          <el-input type="textarea" v-model="formData.descriptions" rows="3"></el-input>
        </el-form-item>
        <el-form-item label="详细内容" prop="content" class="label-right-align">
          <!-- <vue-editor v-model="formData.content"></vue-editor> -->
          <el-input type="textarea" v-model="formData.content" rows="3"></el-input>
        </el-form-item>
        <el-form-item label="启用状态" prop="status" class="label-right-align">
          <el-switch v-model="formData.status"></el-switch>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">提交</el-button>
          <el-button @click="handleTagClose">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>

</template>

<script setup>
  import { ElForm, ElFormItem, ElInput, ElDivider, ElUpload, ElSwitch, ElCard, ElButton, ElMessage } from 'element-plus'
  import 'element-plus/theme-chalk/index.css'
  import { reactive, toRefs, ref, onMounted } from 'vue'
  import axios from '../../../http/index'
  import store from '../../../store/index.ts'; // 引入Vuex store  
  import { getLibrariesById, updateLibraries } from '../../../http/api';

  import { useRouter, useRoute } from 'vue-router';

  const route = useRoute();
  const router = useRouter();

  // 定义组件  
  const formRef = ref(null)
  const fileList = []
  const isUploading = false
  let error = ref(null); // 存储错误的响应式引用  
  const nodeServiceUrl = import.meta.env.VITE_APP_NODE_SERVICE_URL;
  const uploadUrl = nodeServiceUrl + '/api/upload/libraries/single'
  const domain = 'http://up-as0.qiniup.com'
  const qiniuaddr = 'cdn.cryptomanor.xyz'

  // 定义校验规则  
  const rules = reactive({
    title: [{ required: true, message: '标题不可为空', trigger: 'blur' }],
    category: [{ required: true, message: '分类不可为空', trigger: 'blur' }],
    url: [{ required: true, message: '访问地址不可为空', trigger: 'blur' }],
    img: [{ required: true, message: '请上传缩略图', trigger: 'change' }],
    descriptions: [{ required: true, message: '描述不可为空', trigger: 'blur' }],
  })

  // 定义其他响应式数据  
  const imgFileList = reactive([])
  const imgUploadHeaders = reactive({})
  const imgUploadData = reactive({})

  // 定义一个函数来初始化formData  
  function initFormData() {
    return reactive({
      id: '',
      title: "",
      category: '',
      img: null,
      alt: "",
      url: "",
      descriptions: "",
      content: null,
      bgColor: '#ffffff',
      status: true,
    });
  }

  // 初始化formData  
  let formData = initFormData();

  const getDetails = async () => {
    try {
      const id = route.params.id
      const response = await getLibrariesById({
        id: id
      })

      const data = response[0]

      // 直接修改formData的属性，而不是重新创建一个响应式对象  
      formData.id = data.Id;
      formData.title = data.Title;
      formData.category = data.Category;
      formData.img = data.Img;
      formData.alt = data.Alt;
      formData.url = data.Url;
      formData.descriptions = data.Descriptions;
      formData.content = data.Content;
      formData.bgColor = data.bgColor.length > 0 ? data.bgColor : '#ffffff';
      formData.status = data.Status === '1' ? true : false;

      // 清除错误信息（如果需要）  
      error.value = null;
    }
    catch (e) {
      // 重置formData的属性到初始值  
      // 注意：不是重新创建formData对象，而是直接修改它的属性  
      Object.keys(formData).forEach(key => {
        formData[key] = initFormData()[key];
      });

      // 设置错误信息  
      error.value = e.message || '未知错误';
      // 如果需要，你可以添加更多的错误处理逻辑  
    }

  }

  // 重置表单函数  
  let resetForm = () => {
    if (formRef.value && formRef.value.resetFields) {
      formRef.value.resetFields(); // 调用 Element Plus 的 resetFields 方法  
    }
  };

  // 表单验证函数  
  // 表单验证函数  
  const validateForm = async () => {
    try {
      await formRef.value.validate((valid) => {
        if (!valid) {
          // 如果验证失败，通过 ElMessage 显示错误信息  
          formRef.value.validateFields((error, fields) => {
            if (error) {
              const errorMsg = Object.values(fields).map(item => item.message).join('；');
              ElMessage({
                message: '表单验证失败: ' + errorMsg,
                type: 'error',
              });
              return false
            }

            return true
          });
        }
      });

    } catch (error) {
      // 如果在验证过程中发生其他错误，显示错误信息  
      ElMessage({
        message: '表单验证过程中发生错误:',
        type: 'error',
      });
      return false
    } finally {
      console.log('finally')
      return true
    }
  };

  const onSubmit = async () => {
    try {
      // 验证表单  
      if (!validateForm()) {
        return false
      }
      // 如果验证通过，则提交表单  
      const params = { ...formData, alt: formData.title, status: formData.status ? 1 : 0 };
      const response = await updateLibraries(params);
      if (response.code === 0 && response.data.changedRows > 0) {
        ElMessage({
          message: response.msg,
          type: 'success',
        });
        resetForm(formRef); // 重置表单  
        handleTagClose()
      } else {
        ElMessage({
          message: '更新失败: ' + response.msg,
          type: 'error',
        });
      }
    } catch (error) {
      if (error.response) {
        // 请求已发出，服务器也响应了状态码  
        ElMessage({
          message: error.response.data.msg || error.response.data,
          type: 'error',
        });
      } else if (error.request) {
        // 请求已发出，但没有收到任何响应  
        ElMessage({
          message: '请求失败，未收到响应',
          type: 'error',
        });
      } else {
        // 发送请求时发生了些事情，但并未触发错误处理  
        ElMessage({
          message: '请求出错: ' + error.message,
          type: 'error',
        });
      }
    }
  };

  const handleTagClose = () => {
    console.log(route.path, 'currentroute')
    store.dispatch('removeTag', route);
    router.push('/admin/libraries/index')
  };

  const handleProgress = () => { }
  const handleSuccess = () => { }
  const handleError = () => { }

  const handleAvatarSuccess = (res, file) => {
    formData.img = URL.createObjectURL(file.raw);
  }
  const handleRemove = (file, fileList) => {
  }
  const handlePictureCardPreview = (file) => {
    formData.img = file.url;
  }

  // 验证文件合法性
  const beforeUpload = (file) => {
    console.log(file, 'file')
    const isJPG = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/webp' || file.type === 'image/svg+xml';
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!isJPG) {
      // this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
      console.log("上传头像图片只能是 JPG/PNG 格式!")
    }
    if (!isLt2M) {
      // this.$message.error('上传头像图片大小不能超过 2MB!');
      console.log("上传头像图片大小不能超过 2MB!")
    }
    return isJPG && isLt2M;
  }

  // 上传文件到七牛云
  const upqiniuImg = (req) => {

    const config = {
      headers: { 'Content-Type': 'multipart/form-data' }
    }
    let filetype = ''
    if (req.file.type === 'image/png') {
      filetype = 'png'
    } else {
      filetype = 'jpg'
    }

    // 重命名要上传的文件
    const keyname = 'ablum' + (new Date()).valueOf() + Math.floor(Math.random() * 100) + '.' + filetype

    // 从后端获取上传凭证token
    axios.get('/api/qiniu/qiniutoken').then(res => {

      const formdata2 = new FormData()
      formdata2.append('file', req.file)
      formdata2.append('token', res.data.uploadToken)
      formdata2.append('key', keyname)
      // 获取到凭证之后再将文件上传到七牛云空间
      axios.post(domain, formdata2, config).then(res => {
        console.log(res, 'http://' + qiniuaddr + '/' + res.key, 'res-domain')
        formData.img = 'http://' + qiniuaddr + '/' + res.key
        // this.$message.success("图片上传成功")
        console.log("图片上传成功")
      })
    })
  }

  // 在页面加载完成后调用getDetails  
  onMounted(async () => {
    try {
      await getDetails(); // 调用getDetails方法  
    } catch (e) {
      // 错误处理  
      console.error(e);
      error.value = e.message || '未知错误';
    }
  });

</script>

<style lang="scss" scoped>
  .main {
    margin: 20px;
  }

  .el-input-number.full-width-input,
  .el-cascader.full-width-input {
    width: 100% !important;
  }

  .el-form-item--medium {
    .el-radio {
      line-height: 36px !important;
    }

    .el-rate {
      margin-top: 8px;
    }
  }

  .el-form-item--small {
    .el-radio {
      line-height: 32px !important;
    }

    .el-rate {
      margin-top: 6px;
    }
  }

  .el-form-item--mini {
    .el-radio {
      line-height: 28px !important;
    }

    .el-rate {
      margin-top: 4px;
    }
  }

  .clear-fix:before,
  .clear-fix:after {
    display: table;
    content: "";
  }

  .clear-fix:after {
    clear: both;
  }

  .float-right {
    float: right;
  }
</style>

<style lang="scss" scoped>
  div.table-container {
    table.table-layout {
      width: 100%;
      table-layout: fixed;
      border-collapse: collapse;

      td.table-cell {
        display: table-cell;
        height: 36px;
        border: 1px solid #e1e2e3;
      }
    }
  }

  div.tab-container {}

  .label-left-align :deep(.el-form-item__label) {
    text-align: left;
  }

  .label-center-align :deep(.el-form-item__label) {
    text-align: center;
  }

  .label-right-align :deep(.el-form-item__label) {
    text-align: right;
  }

  .custom-label {}

  .static-content-item {
    min-height: 20px;
    display: flex;
    align-items: center;

    :deep(.el-divider--horizontal) {
      margin: 0;
    }
  }
</style>